<template>
  <div class="log-detail-container">
    <div class="page-header">
      <div class="header-left">
        <el-button @click="goBack" icon="ArrowLeft">返回</el-button>
        <h2>请求详情</h2>
      </div>
      <el-button type="danger" @click="deleteLog">删除记录</el-button>
    </div>

    <el-card v-loading="loading" class="detail-card" shadow="never">
      <template v-if="log">
        <div class="basic-info">
          <el-descriptions :column="3" border>
            <el-descriptions-item label="请求ID">{{ log.id }}</el-descriptions-item>
            <el-descriptions-item label="请求方法">
              <el-tag :type="getMethodTagType(log.method)">{{ log.method }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="请求路径">{{ log.path }}</el-descriptions-item>
            <el-descriptions-item label="状态码">
              <el-tag :type="getStatusTagType(log.statusCode)">{{ log.statusCode }}</el-tag>
            </el-descriptions-item>
            <el-descriptions-item label="响应时间">{{ log.responseTime }}ms</el-descriptions-item>
            <el-descriptions-item label="请求时间">{{ formatDate(log.createdAt) }}</el-descriptions-item>
          </el-descriptions>
        </div>

        <el-divider content-position="left">请求详情</el-divider>

        <el-tabs type="border-card">
          <el-tab-pane label="请求头">
            <div class="code-block">
              <pre>{{ formatJSON(log.requestHeaders) }}</pre>
            </div>
          </el-tab-pane>
          <el-tab-pane label="请求体">
            <div class="code-block">
              <pre>{{ formatJSON(log.requestBody) }}</pre>
            </div>
          </el-tab-pane>
          <el-tab-pane label="响应">
            <div class="response-info">
              <div class="response-header">
                <span>状态码: </span>
                <el-tag :type="getStatusTagType(log.statusCode)">{{ log.statusCode }}</el-tag>
              </div>
              <div class="code-block">
                <pre>{{ getResponseBody() }}</pre>
              </div>
            </div>
          </el-tab-pane>
        </el-tabs>
      </template>

      <el-empty v-else-if="!loading" description="未找到请求记录" />
    </el-card>
  </div>
</template>

<script setup>
import { ref, onMounted } from 'vue'
import { useRoute, useRouter } from 'vue-router'
import { ElMessageBox, ElMessage } from 'element-plus'
import { ArrowLeft } from '@element-plus/icons-vue'
import axios from 'axios'

const route = useRoute()
const router = useRouter()
const log = ref(null)
const loading = ref(false)

// 获取日志详情
const fetchLogDetail = async () => {
  const id = route.params.id
  loading.value = true
  try {
    const response = await axios.get(`http://localhost:8080/api/logs/${id}`)
    log.value = response.data
    loading.value = false
  } catch (error) {
    console.error('获取请求日志详情失败:', error)
    ElMessage.error('获取请求日志详情失败')
    loading.value = false
  }
}

// 格式化日期
const formatDate = (dateString) => {
  const date = new Date(dateString)
  return date.toLocaleString()
}

// 格式化JSON
const formatJSON = (jsonString) => {
  if (!jsonString) return '无数据'
  try {
    const obj = typeof jsonString === 'string' ? JSON.parse(jsonString) : jsonString
    return JSON.stringify(obj, null, 2)
  } catch (e) {
    return jsonString
  }
}

// 获取响应体
const getResponseBody = () => {
  if (!log.value || !log.value.responseBody) return '无响应数据'
  return formatJSON(log.value.responseBody)
}

// 根据请求方法获取标签类型
const getMethodTagType = (method) => {
  const methodMap = {
    'GET': 'success',
    'POST': 'primary',
    'PUT': 'warning',
    'DELETE': 'danger',
    'PATCH': 'info'
  }
  return methodMap[method] || ''
}

// 根据状态码获取标签类型
const getStatusTagType = (statusCode) => {
  if (statusCode >= 200 && statusCode < 300) {
    return 'success'
  } else if (statusCode >= 300 && statusCode < 400) {
    return 'info'
  } else if (statusCode >= 400 && statusCode < 500) {
    return 'warning'
  } else {
    return 'danger'
  }
}

//返回上一页
const goBack = () => {
  router.push('/logs')
}

// 删除日志
const deleteLog = async () => {
  try {
    await ElMessageBox.confirm('确定要删除这条请求记录吗？', '提示', {
      confirmButtonText: '确定',
      cancelButtonText: '取消',
      type: 'warning'
    })
    
    const id = route.params.id
    await axios.delete(`http://localhost:8080/api/logs/${id}`)
    ElMessage.success('删除成功') 
    router.push('/logs')
  } catch (error) {
    if (error !== 'cancel') {
      console.error('删除请求日志失败:', error)
      ElMessage.error('删除请求日志失败')
    }
  }
}

onMounted(() => {
  fetchLogDetail()
})
</script>

<style scoped>
.log-detail-container {
  padding: 20px;
}

.page-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 20px;
}

.header-left {
  display: flex;
  align-items: center;
  gap: 15px;
}

.detail-card {
  margin-bottom: 20px;
}

.basic-info {
  margin-bottom: 20px;
}

.code-block {
  background-color: #f5f7fa;
  border-radius: 4px;
  padding: 15px;
  overflow-x: auto;
}

.code-block pre {
  margin: 0;
  white-space: pre-wrap;
  word-wrap: break-word;
}

.response-info {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.response-header {
  display: flex;
  align-items: center;
  gap: 10px;
  margin-bottom: 10px;
}
</style>